package com.atguigu.gmall.mq.receiver;

import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 确认消息
 */
@Component
public class ConfirmReceiver {

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            //            消息持久化
            value = @Queue(
                    value = "queue.confirm", durable = "true", autoDelete = "false"
            ),
            exchange = @Exchange(value = "exchange.confirm"),
            key = {"routing.confirm"}))
    public void getMeag(String message, Message msag, Channel channel) {
        try {
            System.out.println("接受到的消息" + message);

            System.out.println("接受到的消息" + new String(msag.getBody()));

//        确认消息
            long tag = msag.getMessageProperties().getDeliveryTag();
//        false代表一个一个数据确认
//        true代表批量确认
            channel.basicAck(tag, false);
        } catch (IOException e) {
            e.printStackTrace();
//            异常
//            第三个false表示是否重回对列 b是否批量确认消息，b2是否重回队列
            channel.basicNack(msag.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
